package com.zpb.framework.aspect;

import com.alibaba.fastjson.JSON;
import com.zpb.framework.annotation.SysLog;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AdviceName;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @Description:
 * @Author: zhaopengbo
 * @Date: 2025/9/16
 */
@Component
@Aspect
@Slf4j
public class LogAspect {

    @Pointcut("@annotation(com.zpb.framework.annotation.SysLog)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result;
        try {
            handlerBefore(joinPoint);
            result = joinPoint.proceed();
            handlerAfter(result);
        } finally {
            log.info("=======End=======" + System.lineSeparator());
        }
        return result;
    }

    private void handlerBefore(ProceedingJoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//        System.out.println(signature.getMethod().getName());
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        log.info("=======Start=======");
// 打印请求 URL
        log.info("URL :            {}", request.getRequestURL());
// 打印描述信息
        log.info("BusinessName :   {}",signature.getMethod().getAnnotation(SysLog.class).businessName() );
// 打印 Http method
        log.info("HTTP Method :    {}", request.getMethod());
// 打印调用 controller 的全路径以及执行方法
        log.info("Class Method :   {}.{}", signature.getDeclaringTypeName(), signature.getName());
// 打印请求的 IP
        log.info("IP :             {}", request.getRemoteHost());
// 打印请求入参
        log.info("Request Args :   {}", JSON.toJSONString(joinPoint.getArgs()));
    }

    private void handlerAfter(Object result) {
        // 打印出参
        log.info("Response :       {}", JSON.toJSONString(result));
    }
}
